package org.webdb.webapp.picocontainer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.picocontainer.DefaultPicoContainer;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoContainer;
import org.picocontainer.web.PicoScopedContainers;
import org.picocontainer.web.PicoServletContainerListener;
import org.picocontainer.web.ScopedContainers;

public class PicoBootstrap extends PicoServletContainerListener {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static final String PICO_PARENT_NAME = "org.webdb.picocontainer.parent";
    private MutablePicoContainer parentContainer;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        parentContainer = new DefaultPicoContainer();
        parentContainer.setName("stateless");

        event.getServletContext().setAttribute(PICO_PARENT_NAME,
                parentContainer);

        super.contextInitialized(event);
        PicoScopedContainers psc = new PicoScopedContainers(
                getScopedCotainers(event.getServletContext()));

        psc.getApplicationContainer().addAdapter(
                new ServletContextAdapter(ServletContext.class, event
                        .getServletContext()));
        psc.getApplicationContainer().addAdapter(
                new ServletContextAdapter(ServletContext.class.getName(), event
                        .getServletContext()));
    }

    private ScopedContainers getScopedCotainers(ServletContext servletContext) {
        return (ScopedContainers) servletContext
                .getAttribute(ScopedContainers.class.getName());
    }

    /**
     * Esse cara está fornecendo o pai dos pais!
     */
    @Override
    protected PicoContainer makeParentContainer() {
        return parentContainer;
    }

}
